import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:bruno/bruno.dart';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:gal/gal.dart';
import 'package:pro_image_editor/plugins/mime/mime.dart';
import 'vr_phone_capture.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart'; // 添加压缩库

class ImagePreviewPage extends StatefulWidget {
  final XFile imageFile;

  const ImagePreviewPage({Key? key, required this.imageFile}) : super(key: key);

  @override
  _ImagePreviewPageState createState() => _ImagePreviewPageState();
}

class _ImagePreviewPageState extends State<ImagePreviewPage> {
  bool _isLoading = true;
  Uint8List? _imageBytes;
  Uint8List? _compressedBytes; // 存储压缩后的图片
  String _contentType = 'Unknown';

  @override
  void initState() {
    super.initState();
    _processImage(); // 改为处理图片而不是直接加载
  }

  /// 图片处理流程：加载 → 压缩 → 旋转
  Future<void> _processImage() async {
    try {
      // 1. 加载原始图片
      final bytes = await widget.imageFile.readAsBytes();

      // 2. 压缩图片 (质量80%)
      _imageBytes = await FlutterImageCompress.compressWithList(
        bytes,
        quality: 80,
        rotate: 270
      );

      _compressedBytes = _imageBytes; // 保存处理后的图片用于保存

      // 4. 设置MIME类型
      _contentType = lookupMimeType('', headerBytes: _imageBytes) ?? 'image/jpeg';

      setState(() => _isLoading = false);
    } catch (e) {
      debugPrint('Error processing image: $e');
      BrnToast.show('图片处理失败', context);
      // 尝试使用原始图片作为后备
      final fallback = await widget.imageFile.readAsBytes();
      setState(() {
        _imageBytes = fallback;
        _compressedBytes = fallback;
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        elevation: 0,
        actions: [
          Spacer(),
          IconButton(
            icon: Image.asset('assets/icon_close.png'),
            onPressed: () async => _navigateBackToCamera(),
          ),
        ],
      ),
      body: Container(
        color: Colors.black,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Expanded(
              child: _isLoading
                  ? const Center(child: CircularProgressIndicator(color: Colors.white))
                  : Image.memory(_imageBytes!, fit: BoxFit.contain),
            ),
            _buildBottomControls(),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomControls() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 重拍按钮
        Padding(
          padding: const EdgeInsets.only(right: 50),
          child: GestureDetector(
            onTap: () async => _navigateBackToCamera(),
            child: Row(
              children: [
                const Text('重拍', style: TextStyle(fontSize: 16, color: Colors.white)),
                const SizedBox(width: 8),
                Image.asset('assets/phone_recapture.png', width: 24),
              ],
            ),
          ),
        ),

        // 满意按钮
        IconButton(
          icon: Image.asset('assets/icon_confirm.png', width: 48),
          onPressed: _onConfirmPressed,
        ),
        const SizedBox(width: 98),
      ],
    );
  }

  /// 返回相机页面
  Future<void> _navigateBackToCamera() async {
    final cameras = await availableCameras();
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(
        builder: (context) => TakePictureScreen(camera: cameras.first),
      ),
    );
  }

  /// 确认按钮处理
  Future<void> _onConfirmPressed() async {
    if (_compressedBytes == null) {
      BrnToast.show("图片未处理完成，请稍后再试", context);
      return;
    }

    BrnLoadingDialog.show(context, content: "保存中...");

    try {
      // 1. 保存到相册
      await _saveToGallery();

      // 2. 保存到上传目录
      await _saveToUploadDirectory();

      // 3. 关闭加载提示并退出页面
      BrnLoadingDialog.dismiss(context);
      Navigator.pop(context); // 返回上一页

    } catch (e) {
      BrnLoadingDialog.dismiss(context);
      debugPrint('保存失败: $e');
      BrnToast.show("保存失败，请重试", context);
    }
  }

  /// 保存到相册
  Future<void> _saveToGallery() async {
    try {
      // 检查相册权限
      final hasAccess = await Gal.hasAccess();
      if (!hasAccess && await Gal.requestAccess() == false) {
        throw Exception('相册权限被拒绝');
      }

      // 生成带时间戳的文件名
      final fileName = _generateFileName(_contentType);

      // 保存到相册
      await Gal.putImageBytes(_compressedBytes!, name: fileName);
    } catch (e) {
      debugPrint('保存到相册失败: $e');
      rethrow;
    }
  }

  /// 保存到上传目录
  Future<void> _saveToUploadDirectory() async {
    try {
      // 获取应用文档目录
      final appDocDir = await getApplicationDocumentsDirectory();

      // 创建pano子目录（如果不存在）
      final panoDir = Directory('${appDocDir.path}/pano');
      if (!await panoDir.exists()) {
        await panoDir.create(recursive: true);
      }

      // 生成带时间戳的文件路径
      final fileName = _generateFileName(_contentType);
      final filePath = '${panoDir.path}/$fileName';

      // 写入文件
      final file = File(filePath);
      await file.writeAsBytes(_compressedBytes!);

      debugPrint('图片已保存到: $filePath');
    } catch (e) {
      debugPrint('保存到上传目录失败: $e');
      rethrow;
    }
  }

  /// 生成带时间戳的文件名
  String _generateFileName(String contentType) {
    final timeStamp = DateTime.now().millisecondsSinceEpoch;
    final extension = contentType.split('/').last;
    return 'pano_$timeStamp.$extension';
  }
}